package com.jvxb.demo.utils;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.generator.FastAutoGenerator;
import com.baomidou.mybatisplus.generator.config.OutputFile;
import com.baomidou.mybatisplus.generator.config.rules.DateType;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.fill.Column;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 代码生成工具类
 *
 * @author jvxb
 * @since 2022-12-11
 * @示例样表如下：
    CREATE DATABASE IF NOT EXISTS `demo` DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
    ​DROP TABLE IF EXISTS `demo`.`sys_user`;
    CREATE TABLE `demo`.`sys_user` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键',
    `role_id` int(11) DEFAULT NULL COMMENT '所属角色id',
    `role_name` varchar(50) DEFAULT NULL COMMENT '所属角色 (冗余设计)',
    `user_name` varchar(50) NOT NULL COMMENT '用户名',
    `user_code` varchar(50) DEFAULT NULL COMMENT '用户code',
    `login_name` varchar(50) DEFAULT NULL COMMENT '登录名',
    `password` varchar(50) NOT NULL COMMENT '登录密码',
    `phone` varchar(11) DEFAULT NULL COMMENT '手机号码',
    `valid` int(1) DEFAULT '1' COMMENT '帐号是否有效 0 无效 1有效',
    `create_time` datetime DEFAULT NULL COMMENT '创建时间',
    `update_time` datetime DEFAULT NULL COMMENT '更新时间',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='系统用户表';
 */
public class CodeGenerateUtil {
    //  配置需要生成的表名（多个用逗号隔开）、数据库连接
    private static final String TABLES = "sys_user";
    private static final String URL = "jdbc:mysql://localhost:3306/demo?useUnicode=true&serverTimezone=GMT%2B8&characterEncoding=utf8&useSSL=false";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";
    private static final String AUTHOR = "jvxb";
    //  -----------------------------------------------------------------------------
//  是否开启覆盖已生成的 Entity 和 Mapper文件（为防止覆盖原有方法，默认不允许覆盖。字段变化时建议手动处理）
  private static final boolean OVERRIDE_ENTITY_MAPPER = false;
//    private static final boolean OVERRIDE_ENTITY_MAPPER = true;
    //  -----------------------------------------------------------------------------
//  当前项目路径，父包名与模块名（projectDir\src\main\java下的模块）
    private static final String projectDir = System.getProperty("user.dir");
    private static final String PARENT_PACKAGE_NAME = "com.jvxb";
    private static final String MODULE_NAME = "demo";

    public static void main(String[] args) {
        //生成代码
        generateCode();
        //删除代码
//        deleteCode();
    }

    public static void generateCode() {
        FastAutoGenerator.create(URL, USERNAME, PASSWORD)
                .globalConfig(builder -> {
                    builder.author(AUTHOR) // 设置作者
                            .enableSwagger() // 开启 swagger 模式
                            .disableOpenDir() //生成代码后不打开目录
                            .dateType(DateType.ONLY_DATE) //使用 Date
                            .outputDir(projectDir + "\\src\\main\\java"); // 指定输出目录
                })
                .packageConfig(builder -> {
                    builder.parent(PARENT_PACKAGE_NAME) // 设置父包名
                            .moduleName(MODULE_NAME) // 设置父包模块名
                            .pathInfo(Collections.singletonMap(OutputFile.xml,
                                    projectDir + "\\src\\main\\resources\\com.jvxb.demo.mapper")); // 设置mapperXml生成路径
                })
                .strategyConfig(builder -> {
                    builder.addInclude(TABLES);
                    builder.controllerBuilder()
                            .enableRestStyle();
                    builder.serviceBuilder()
                            .formatServiceFileName("%sService");
                    builder.entityBuilder()
                            .addTableFills(new Column("create_time", FieldFill.INSERT))
                            .addTableFills(new Column("update_time", FieldFill.INSERT_UPDATE))
                            .enableColumnConstant()
                            .enableLombok();
                    builder.mapperBuilder()
                            .enableBaseResultMap() // 开启BaseResultMap
                            .enableBaseColumnList(); // 开启BaseColumnList
                    if (OVERRIDE_ENTITY_MAPPER) {
                        builder.entityBuilder().fileOverride();
                        builder.mapperBuilder().fileOverride();
                    }
                })
                .execute();
    }


    private static void deleteCode() {
        for (String table : TABLES.split(",")) {
            String entityName = NamingStrategy.capitalFirst(NamingStrategy.underlineToCamel(table));
            String parentPackageName = PARENT_PACKAGE_NAME.replace(".", "\\");
            List<String> pathArr = new ArrayList<>();
            pathArr.add(String.format("%s\\src\\main\\java\\%s\\%s\\com.jvxb.demo.controller\\%sController.java", projectDir, parentPackageName, MODULE_NAME, entityName));
            pathArr.add(String.format("%s\\src\\main\\java\\%s\\%s\\com.jvxb.demo.service\\%sService.java", projectDir, parentPackageName, MODULE_NAME, entityName));
            pathArr.add(String.format("%s\\src\\main\\java\\%s\\%s\\com.jvxb.demo.service\\impl\\%sServiceImpl.java", projectDir, parentPackageName, MODULE_NAME, entityName));
            pathArr.add(String.format("%s\\src\\main\\java\\%s\\%s\\com.jvxb.demo.entity\\%s.java", projectDir, parentPackageName, MODULE_NAME, entityName));
            pathArr.add(String.format("%s\\src\\main\\java\\%s\\%s\\com.jvxb.demo.mapper\\%sMapper.java", projectDir, parentPackageName, MODULE_NAME, entityName));
            pathArr.add(String.format("%s\\src\\main\\resources\\com.jvxb.demo.mapper\\%sMapper.xml", projectDir, entityName));
            for (String path : pathArr) {
                File file = new File(path);
                if (file.exists()) {
                    System.out.println(String.format("delete file [%s] ...", file.getAbsolutePath()));
                    file.delete();
                } else {
                    System.out.println(String.format("file [%s] does not exist", file.getAbsolutePath()));
                }
            }
        }
    }
}
